import { create } from "zustand";
import { Friend, FriendUpdateType } from "@/types/friend";
import { deleteFriend, updateFriendRemark } from "@/services/api/friend";
import { ResponseCode } from "@/types/api-common";
import { UserProfileType } from "@/types/user-profile";

interface FriendsState {
  state: {
    friends: Friend[];
    totalUnreadFriendRequests: number; // 未读好友请求总数
    loading: boolean;
    error: Error | null;
    currentFriend: UserProfileType;
  };
  actions: {
    setLoading: (loading: boolean) => void;
    setTotalUnreadFriendRequests: (count: number) => void;
    setError: (error: Error | null) => void;
    setFriendInfo: (friend: UserProfileType) => void;
    setFriends: (friends: Friend[]) => void;
    updateFriend: (friend: FriendUpdateType) => void;
    addFriend: (friend: Friend) => Promise<void>;
    removeFriend: (friendId: string) => Promise<void>;
    updateFriendRemark: (friendId: string, remark: string) => Promise<void>;
  };
}

const FriendsStateStore = create<FriendsState>((set, get) => ({
  state: {
    friends: [],
    totalUnreadFriendRequests: 0,
    currentFriendUUID: "",
    currentFriend: null,
    loading: false,
    error: null,
  },
  actions: {
    setFriendInfo(friend: UserProfileType): void {
      set((state) => ({
        state: {
          ...state.state,
          currentFriend: friend,
        },
      }));
    },
    setLoading(loading: boolean): void {
      set((state) => ({
        state: {
          ...state.state,
          loading,
        },
      }));
    },
    setTotalUnreadFriendRequests(count: number): void {
      set((state) => ({
        state: {
          ...state.state,
          totalUnreadFriendRequests: count,
        },
      }));
    },
    setError(error: Error | null): void {
      set((state) => ({
        state: {
          ...state.state,
          error,
        },
      }));
    },
    setFriends(friends: Friend[]): void {
      set((state) => {
        // 确保创建新的数组引用，即使数据相同
        const newFriends = [...friends];
        return {
          state: {
            ...state.state,
            friends: newFriends,
            error: null, //清除错误信息状态
          },
        };
      });
      setTimeout(() => {
        const currentState = get().state;
        console.log("设置好友后的状态:", {
          friendsCount: currentState.friends?.length || 0,
          error: currentState.error ? currentState.error.message : null,
        });
      }, 0);
    },
    updateFriend(friend: FriendUpdateType): void {
      set((state) => {
        const updatedFriends = state.state.friends.map((f) => {
          if (f.id === friend.friendId) {
            return {
              ...f,
              remark: friend.remark ?? f.remark,
              friendStatus: friend.friendStatus ?? f.friendStatus,
              lastOnlineTime: friend.lastOnlineTime ?? f.lastOnlineTime,
            };
          }
          return f;
        });
        return {
          state: {
            ...state.state,
            friends: updatedFriends,
          },
        };
      });
    },
    //添加朋友
    async addFriend(friend: Friend) {
      //TODO
    },
    //更新朋友的备注
    async updateFriendRemark(friendId: string, remark: string) {
      const resp = await updateFriendRemark({
        remark,
        friendId: get().state.currentFriend.id,
      });
      if (resp.data.code === ResponseCode.SUCCESS) {
        set((state) => ({
          state: {
            ...state.state,
            friends: state.state.friends.map((f) =>
              f.id === friendId ? { ...f, remark } : f
            ),
          },
        }));
      }
    },
    //删除朋友
    async removeFriend(friendId: string) {
      const resp = await deleteFriend(friendId);
      if (resp.data.code === ResponseCode.SUCCESS) {
        set((state) => ({
          state: {
            ...state.state,
            friends: state.state.friends.filter((f) => f.id !== friendId),
          },
        }));
      }
    },
  },
}));

export default FriendsStateStore;
